package kr.hkit.androidcomplete03.ch22;

import java.util.ArrayList;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;



public class SurView extends SurfaceView implements Callback {
	ArrayList<Ball> arBall;
	final static int DELAY = 50;
	
	SurfaceHolder mHolder;
	DrawThread mThread;
	
	public SurView(Context context) {
		super(context);
		mHolder = getHolder();
		mHolder.addCallback(this);
		arBall = new ArrayList<>();
	}
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_DOWN){
			synchronized (mHolder) {
				Ball newBall = Ball.create((int)event.getX(), (int)event.getY());
				arBall.add(newBall);
			}
			return true;
		}
		return false;
	}
	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		mThread = new DrawThread(mHolder);
		mThread.start();
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,	int height) {
		if (mThread != null){
			mThread.sizeChange(width, height);
		}
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		mThread.bExit = true;
		for(;;){
			try {
				mThread.join();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	public class DrawThread extends Thread{
		boolean bExit;
		int mWidth;
		int mHeight;
		SurfaceHolder mHolder;
		
		public DrawThread(SurfaceHolder mHolder) {
			this.mHolder = mHolder;
		}
		
		public void sizeChange(int width, int height){
			mWidth = width;
			mHeight = height;
		}

		public void run() {
			Canvas canvas;
			Ball B;
			
			while(!bExit){
				for(int i=0; i<arBall.size(); i++){
					B = arBall.get(i);
					B.move(getWidth(), getHeight());
					if (B.count > 4){
						arBall.remove(i);
						i--;
					}
				}//end of for
				
				synchronized (mHolder) {
					canvas = mHolder.lockCanvas();
					//그리기
					if (canvas == null)break;
					canvas.drawColor(Color.WHITE);
					
					for(int i=0; i<arBall.size(); i++){
						arBall.get(i).draw(canvas);
						if (bExit) break;
					}
					mHolder.unlockCanvasAndPost(canvas);
				}
				try {sleep(SurView.DELAY);} catch (InterruptedException e) {}
			}//end of while
		}//end of method run
	}//end of class DrawThread

}
